import Base from 'models/base';

import moment from 'moment';

export default class GoodsActivityForm extends Base {
  file = null;
  fileName = '';
  fileSize = '';
  mimeType = '';
  prefix = '';

  constructor(fileData) {
    super();

    if (fileData === undefined) {
      return;
    }

    let fields = ['id', 'fileName', 'fileSize', 'mimeType', 'qiqiuUrl', 'status', 'type'];
    this.initObject(fileData, fields);

    let time = fileData.addTime;
    this.time = moment(time).valueOf();

    this.calFileSize();
  }

  setFile(file) {
    this.file = file;
    this.fileName = file.name;
    this.mimeType = file.type;
    this.fileSize = file.size;

    this.calFileSize();
  }

  calFileSize() {
    let fileSize = this.fileSize;
    let count, unit;
    if (fileSize < 1024) {
      count = fileSize;
      unit = 'B';
    } else if (fileSize < 1024 * 1024) {
      count = _.round(fileSize / 1024, 2);
      unit = 'KB';
    } else if (fileSize < 1024 * 1024 * 1024) {
      count = _.round(fileSize / (1024 * 1024), 2);
      unit = 'MB';
    } else if (fileSize < 1024 * 1024 * 1024 * 1024) {
      count = _.round(fileSize / (1024 * 1024 * 1024), 2);
      unit = 'GB';
    } else if (fileSize < 1024 * 1024 * 1024 * 1024 * 1024) {
      count = _.round(fileSize / (1024 * 1024 * 1024 * 1024), 2);
      unit = 'TB';
    }
    this.size = count + unit;
  }

  checkValid() {
    let fields = ['file', 'fileName'];
    return this.checkRequired(fields);
  }

  getUploadFile() {
    let fileName = this.fileName;
    let prefix = this.prefix.trim();
    let key = fileName;
    if (prefix !== '') {
      key = prefix + fileName;
    }

    let file = this.file;
    return {
      file,
      key,
      fileName
    };
  }
}
